﻿using System;

namespace haoyougen
{
    /*
        一些与java不同的特性
     */
    class HelloWorld
    {
        static void test()
        {
            dynamic d2 = new Dog(  //dynamic动态类型，运行时确定类型
                @"\test", //@下的字符串不用转码
                4
            );   
            Console.WriteLine("name:{0}", d2.getName());    //{n}占位符
            Console.WriteLine(d2.getLeg().ToString());      //基本类型也有ToString方法
            Dog d3 = d2.getName() as Dog;       //as 强转，转换失败也不会抛异常

            int[] arrs = {0, 1, 2, 3, 4};  //数组定义
            foreach (dynamic i in arrs){   //for each循环
                Console.WriteLine(i);
            }

            int x = 3;
            int y = 4;
            MathUtil.swap(ref x, ref y);             //ref 引用。c++中的&
            Console.WriteLine("swap:{0}{1}", x, y);

            float a = 1, b = 2, c = 1;
            float x1,x2;
            bool hasAns = MathUtil.linearEquations(a, b, c, out x1, out x2);     //out与ref的区别在与ref必须先初始化
            if (hasAns)
                Console.WriteLine("{0}x²+{1}x+{2}=0的解为：x1={3}，x2={4}", a, b, c, x1, x2);
            else 
                Console.WriteLine("{0}x²+{1}x+{2}=0方程无解", a, b, c);
            
            //int ui = null;  基本类型是不能赋值null的
            int? ni = null;   //加上问号后即可，等价于Nullable<int> ni = new Nullable<int>(null);
            int j = ni ?? 3;  //j=ni如果ni为null则等于3
            Console.WriteLine("ni为null，所以j为3：{0}", j);

        }
    }
    class Animal
    {
        private char sex;
    }
    class Dog : Animal
    {
        private string name;
        private int leg;

        public string getName()
        {
            return name;
        }
        public int getLeg()
        {
            return leg;
        }
        public Dog(string name, int leg)
        {
            this.name = name;
            this.leg = leg;
        }
    }

    class MathUtil
    {
        static public void swap(ref int x, ref int y)
        {
            int temp = x;
            x = y;
            y = temp;
        }

        static public bool linearEquations(float a, float b, float c, out float x1, out float x2)
        {
            float k = b * b - 4 * a * c;
            if (k >= 0)
            {
                x1 = (-b + k) / 2 * a;
                x2 = (-b - k) / 2 * a;
                return true;
            }
            else 
            {
                x1 = 0;
                x2 = 0;
                return false;
            }
        }
    }
}
